const app = getApp();
const api = require("../../server/Api.js");
Page({

  data: {
    emptyType: 11,
    isEmpty: false,
    opactiy: 0,
    shops: []
  },

  onLoad: function(options) {

  },

  onReady: function() {

  },

  onShow: function() {
    this.refreshCartList();
  },

  onPullDownRefresh: function() {
    this.refreshCartList();
  },

  //查询购物车列表
  refreshCartList: function() {
    // tt.showNavigationBarLoading()
    this.queryCartList(1, 100);
  },

  // 分页查询首页数据
  queryCartList: function(page, pageSize) {
    let that = this;
    let userInfo = app.globalData.userBean;
    if (!userInfo || !userInfo.consumerId) {
      // tt.hideNavigationBarLoading()
      tt.stopPullDownRefresh();
      that.setData({
        shops: []
      })
      return;
    }

    //请求账号登陆接口
    let prams = {
      pageSize: pageSize,
      pageNumber: page,
      platformId: app.globalData.platformId,
      userId: userInfo.consumerId
    };

    api.queryCartList(prams).then(res => {
      that.querySuccess(res, page)
      tt.stopPullDownRefresh();
      that.setData({
        emptyType: 11
      })
    }).catch(msg => {
      tt.stopPullDownRefresh();
      var message = typeof msg == "string" ? msg : msg.message;
      that.setData({
        emptyType: 101
      })
      app.showToast(message);
    })
  },

  //查询购物车成功
  querySuccess: function(res, curPage) {
    let that = this;
    console.log("购物车", res);
    let total = 0;
    for (let i = 0; i < res.records.length; i++) {
      for (let j = 0; j < res.records[i].cartVO.length; j++) {
        res.records[i].cartVO[j].skuImage = app.resetImageUrl(res.records[i].cartVO[j].skuImage, 172, 172);
        total += parseInt(res.records[i].cartVO[j].goodsQuantity)
      }
    }
    app.globalData.cartCount = total;
    app.setTabBarBadge();
    that.setData({
      shops: res.records
    })


    //计算购物车总金额
    this.computerAmount();

    //计算购物车商品数量
    // let goodsQuantity = 0;
    // if (res.records.length > 0) {
    //   for (let a = 0; a < res.records.length; a++) {
    //     goodsQuantity += parseInt(res.records[a].goodsQuantity)
    //   }
    // }

    // if (goodsQuantity > 0) {
    //   tt.setTabBarBadge({
    //     index: 1,
    //     text: '' + goodsQuantity
    //   })
    // } else {
    //   tt.removeTabBarBadge({
    //     index: 1,
    //   })
    // }
    // app.globalData.cartGoodsNum = goodsQuantity;
  },

  onReachBottom: function() {

  },
  //结算
  toSubmit: function(e) {
    console.log(e);
    let items = e.currentTarget.dataset.items;
    let checkedItems = [];
    for (var i = 0; i < items.length; i++) {
      if (items[i].goodsQuantity) {
        checkedItems.push(items[i]);
      }
    }

    if (checkedItems.length <= 0) {
      app.showToast("您还没有选中商品哦！")
      return;
    }
    let itemsJson = JSON.stringify(checkedItems);
    itemsJson = itemsJson.replace(/\?/g, "-|-").replace(/\=/g, "-||-");
    tt.navigateTo({
      url: '../cart-confirm-order/cart-confirm-order?items=' + itemsJson,
    })
  },
  removeShop(e) {
    let userInfo = app.globalData.userBean;
    if (!(userInfo && userInfo.consumerId)) {
      tt.navigateTo({
        url: '../login/login',
      })
    }
    api.deleteCartByStoreId(e.currentTarget.dataset.id, userInfo.consumerId).then(res => {
      this.refreshCartList();
    }).catch(() => {
      app.showToast("清除购物车失败!");
    })
  },
  //计算购物车总金额
  computerAmount: function(e) {
    let shopList = this.data.shops;
    for (var i = 0; i < shopList.length; i++) {
      let totalAmount = 0;
      if (shopList[i].cartVO) {
        for (var j = 0; j < shopList[i].cartVO.length; j++) {
          totalAmount += (parseFloat(shopList[i].cartVO[j].goodsPrice) * 100 * parseInt(shopList[i].cartVO[j].goodsQuantity)) / 100;
        }
      }
      shopList[i].totalAmount = totalAmount.toFixed(2);
    }
    this.setData({
      shops: shopList,
    })
  },
  refreshCart: function(e) {
    let that = this;
    for (let i = 0; i < that.data.shops.length; i++) {
      if (that.data.shops[i].storeId == e.detail.goods.storeId) {
        for (let j = 0; j < that.data.shops[i].cartVO.length; j++) {
          if (that.data.shops[i].cartVO[j].skuId == e.detail.goods.skuId) {
            that.data.shops[i].cartVO[j].goodsQuantity = e.detail.goods.goodsQuantity;
            that.data.shops[i].cartVO[j].recId = e.detail.goods.recId;
            that.setData({
              shops: that.data.shops
            })
            that.computerAmount();
            break;
          }
        }
        break;
      }
    }
  },
  delCart(e) {
    api.deleteCart(e.detail.goods.recId).then(res => {
      this.refreshCartList();
    }).catch(() => {
      app.showToast("删除购物车项失败!");
    })
  },
  leftMove(e) {
    for (let i = 0; i < this.data.shops.length; i++) {
      for (let j = 0; j < this.data.shops[i].cartVO.length; j++) {
        console.log(e.detail.cur.spuId != this.data.shops[i].cartVO[j].spuId)
        if (e.detail.cur.spuId != this.data.shops[i].cartVO[j].spuId) {
          this.data.shops[i].cartVO[j].scrollLeft = 0
        }
      }
    }
    this.setData({
      shops: this.data.shops
    })
  }
})